﻿using MCUPackage.DesignEditor;
using MCUPackage.Utils;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel;

namespace SxPackages.STC8.Models
{
	/// <summary>
	/// SPI选项
	/// </summary>
	[Serializable]
	abstract class SPIOptionBase
	{
		protected STC8HUSOP20 mParent = null;

		/// <summary>
		/// SPI类型
		/// </summary>
		[Browsable(false)]
		public SPITypes Type { get; protected set; }
		/// <summary>
		/// 使用的引脚名结合
		/// </summary>
		protected string[] mUsePins { get; set; }
		protected abstract void SetPins(string[] aPins);

		/// <summary>
		/// 切换引脚
		/// </summary>
		/// <param name="aNew"></param>
		/// <param name="aOld"></param>
		/// <returns>是否切换成功</returns>
		protected bool SwitchPins(string aNew, string aOld)
		{
			string[] newPins = TemplateHelper.GetPins(aNew);
			string[] oldPins = TemplateHelper.GetPins(aOld);

			if (this.Enable)
			{
				if (mParent.PinIsUsedTips(newPins))
				{
					return false;
				}
				// 清除占用的功能脚
				mParent.ResetPins(oldPins);
				SetPins(newPins);
			}

			mUsePins = newPins;
			return true;
		}

		private bool mEnable = false;
		[DisplayName("使能"),
		DefaultValue(false),
		JsonProperty(Order = 100),
		Description("是否使能本SPI口"),
		PropertyOrder(0)]
		public virtual bool Enable
		{
			get => mEnable;
			set
			{
				if (value != mEnable)
				{
					if (value)
					{
						if (mParent.PinIsUsedTips(mUsePins))
						{
							return;
						}
						// 设置引脚用途
						SetPins(mUsePins);
					}
					else
					{
						// 清除占用的功能脚
						mParent.ResetPins(mUsePins);
					}
					mEnable = value;
				}
			}
		}

		public override String ToString()
		{
			return string.Empty;
		}

		public abstract Boolean AppendConfig(List<String[]> aLst);

		public SPIOptionBase(STC8HUSOP20 aParent)
		{
			this.mParent = aParent;
		}
	}
}
